<template>
  <div>
    <!-- 导航 -->
    <div class="flex">
      <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item><a href="/">banners管理</a></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 操作栏 -->
      <div class="flex" style="line-height: 40px">
        <span>状态筛选：</span>
        <el-select
          v-model="value"
          placeholder="请选择"
          filterable
          @change="change"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 按钮组 -->
        <el-row>
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加banner</el-button
          >
          <el-button type="primary" @click="toggleSelection((index = '上架'))"
            >上架</el-button
          >
          <el-button type="warning" @click="toggleSelection((index = '下架'))"
            >下架</el-button
          >
          <el-button type="danger" @click="toggleSelection((index = '删除'))"
            >删除</el-button
          >
        </el-row>
        <!-- 添加弹出层 -->
        <el-dialog title="banners管理" :visible.sync="dialogFormVisible">
          <div class="left" style="margin-top: 15px">
            banners图像：
            <el-upload
              class="upload-demo"
              drag
              action="/api/banners/upload"
              :before-upload="scpic"
              :on-success="handleget"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </div>

          <div class="left" style="margin-top: 15px">
            banners序号：
            <el-input
              v-model="input_num"
              placeholder="请输入内容"
              style="width: 200px"
            ></el-input>
          </div>

          <div class="left" style="margin-top: 15px">
            banners备注：
            <el-input
              v-model="input_notes"
              placeholder="请输入内容"
              style="width: 200px"
            ></el-input>
          </div>

          <div class="left" style="margin-top: 15px">
            banners状态：
            <el-input
              v-model="input_status"
              placeholder="请输入内容"
              style="width: 200px"
            ></el-input>
          </div>

          <div class="left" style="margin-top: 15px">
            banners创建时间：
            <el-input
              v-model="input_time"
              placeholder="请输入内容"
              style="width: 200px"
            ></el-input>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="(dialogFormVisible = false), upload()">确 定</el-button>
            <el-button @click="dialogFormVisible = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
    <!-- 表单 -->
    <div style="margin-top: 20px" v-loading="loading">
      <!-- 基础设置 -->
      <!-- ：data为表单绑定的数组 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        max-height="500"
        type="index"
        :default-sort="{ prop: 'num', order: 'ascending' }"
        align="left"
        @select="getrows"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column fixed prop="num" label="序号" width="250">
        </el-table-column>
        <el-table-column prop="notes" label="备注" width="120">
        </el-table-column>

        <el-table-column prop="tableData" label="图片" width="300">
          <template slot-scope="scope">
            <el-image style="width: 200px; height: 100px"  :src="'/api/images/banners/'+scope.row.url" fit="fit"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="100%">
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click.native.prevent="
                (dialogVisible = true), handleEdit(scope.$index, scope.row)
              "
              size="small"
            >
              编辑
            </el-button>

            <el-button
              @click.native.prevent="deleteRow(scope.$index, scope.row)"
              type="danger"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑banners操作区 -->
      <el-dialog title="编辑banners" :visible.sync="dialogVisible" width="30%">
        <!-- 映射修改按钮弹出层的对应数据 -->
        <el-form>
          <!-- 序号 -->
          <el-form-item label="序号：" :label-width="formLabelWidth">
            <el-input
              v-model="num"
              placeholder="请输入内容"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
          <!-- 备注 -->
          <el-form-item label="备注：" :label-width="formLabelWidth">
            <el-input
              v-model="notes"
              placeholder="请输入内容"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
          <!-- 路径 -->
          <el-form-item label="路径：" :label-width="formLabelWidth">
            <el-image :src="this.url"></el-image>
          </el-form-item>
          <!-- 状态 -->
          <el-form-item label="状态：" :label-width="formLabelWidth">
            <el-input
              v-model="status"
              placeholder="请输入内容"
              style="width: 400px"
            >
            </el-input>
            <!-- 创建时间 -->
          </el-form-item>
          <el-form-item label="创建时间：" :label-width="formLabelWidth">
            <el-input
              v-model="createTime"
              placeholder="请输入内容"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 修改弹出层的操作按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false"> 取 消 </el-button>
          <el-button
            type="primary"
            @click="(dialogVisible = false), handlechange()"
          >
            确 定
          </el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addBanners } from "@/services/bannersService";
import { deleteBanners } from "@/services/bannersService";
import { putBanners } from "@/services/bannersService";
import { getAllbanners } from "@/services/bannersService";
export default {
  data() {
    return {
      formLabelWidth: "120px",
      tableData: [],
      options: [
        {
          value: "全部",
          label: "全部",
        },
        {
          value: "未上架",
          label: "未上架",
        },
        {
          value: "已上架",
          label: "已上架",
        },
        {
          value: "已下架",
          label: "已下架",
        },
      ],
      value: "",
      loading: true,
      dialogFormVisible: false,
      dialogVisible: false,
      notes: "",
      num: "",
      url: "",
      status: "",
      createTime: "",
      index: "",
      rows: [],
      input_notes:'',
      input_name:'',
      input_num:'',
      input_status:'未上架',
      input_time:'',
      file:{},
    };
  },
  methods: {

    async upload(){
      let upurl = this.file.filename
      await addBanners(this.input_num, this.input_notes, upurl, this.input_status, this.input_time);
      this.loading = true;
      this.render();
      this.loading = !this.loading
    },
    getrows(row) {
      // 得到勾选的数据
      this.rows = row;
    },
    // 状态修改
    async toggleSelection(index) {
      console.log(index);
      switch (index) {
        // 上架按钮
        case "上架": {
          console.log(index);
          // 将勾选的数据过滤
          let result = this.rows.filter((item) => item.status == "已上架");
          // 当过滤后的数据中有已上架的状态则提示
          if (result.length > 0) {
            this.$alert("已有上架的banners", "警告", {
              confirmButtonText: "确定",
            });
          } else {
            // 若存在多选的情况，需要遍历将数据状态进行修改
            for (let i = 0; i < this.rows.length; i++) {
              // 将得到的数据解构并修改status的值
              let { _id, num, notes, url, status, createTime } = this.rows[i];
              status = "已上架";
              // 异步调用后台数据给一个加载效果
              this.loading = true;
              await putBanners(_id, num, notes, url, status, createTime);
            }
            this.loading = !this.loading;
            // 成功则弹出框提示成功并重新渲染表格
            this.$alert("上架成功！", "提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.render();
              },
            });
          }
          break;
        }
        // 下架按钮
        case "下架": {
          let result = this.rows.filter((item) => item.status == "已下架");
          if (result.length > 0) {
            this.$alert("已有下架的banners", "警告", {
              confirmButtonText: "确定",
            });
          } else {
            for (let i = 0; i < this.rows.length; i++) {
              console.log(this.rows[i]);
              let { _id, num, notes, url, status, createTime } = this.rows[i];
              status = "已下架";
              console.log(_id, num, notes, url, status, createTime);
              this.loading = true;
              await putBanners(_id, num, notes, url, status, createTime);
            }
            this.loading = !this.loading;
            this.$alert("下架成功！", "提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.render();
              },
            });
          }
          break;
        }
        // 删除按钮
        case "删除": {
          let resp = ''
          for (let i = 0; i < this.rows.length; i++) {
            resp = await deleteBanners(this.rows[i]._id);
          }
          if (resp) {
            this.$alert("删除banners成功！", "提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.render();
              },
            });
          }
        }
      }
    },
    // e 为select选择器上的value值
    // 通过比对select选择器上的value值和数据中的状态值可以筛选出符合条件的数据
    async change(e) {
      //异步获取后端数据给一个加载效果
      this.loading = true;
      let resp = await getAllbanners();
      this.loading = !this.loading;
      // 比对数据
      let result = resp.filter((item) => item.status == e);
      if (result) {
        this.tableData = result;
      }
      if (e == "全部") {
        this.tableData = resp;
      }
    },
    // 修改数据
    handlechange() {
      console.log(this.index);
      // 调用修改数据方法
      this.changeBanners();
      // 修改数据后重新渲染
      this.render();
    },
    //将该行的数据映射到弹出层上
    handleEdit(index, rows) {
      console.log(index,rows)
      // 展开后将获取的数据关联到输入框中
      this.notes = rows.notes;
      this.num = rows.num;
      this.url = "/api/images/banners/"+rows.url;
      this.status = rows.status;
      this.createTime = rows.createTime;
      this.index = rows._id;
    },
    // 删除数据
    async deleteRow(index, rows) {
      // 删除数据库中的内容
      await deleteBanners(rows._id);
      
      this.loading = true;
      this.render();
      this.loading = !this.loading
    },

    handleget(response, file,){
      console.log(response)
      console.log("======")
      console.log(file)
      this.file = response;
    },
    // 上传图片
    scpic(file) {
      console.log(file)
      console.log(file.uid);
      console.log("=========");
    },
    // 修改数据
    async changeBanners() {
      await putBanners(
        this.index,
        this.num,
        this.notes,
        this.url,
        this.status,
        this.createTime
      );
    },
    // 渲染数据
    async render() {
      this.$store.dispatch("bannersStore/getBannersData").then(() => {
        this.loading = true;
        this.tableData = this.$store.state.bannersStore.banners;
        this.loading = !this.loading;
      });
    },
  },
  // 默认渲染内容
  async created() {
    this.render();
    let date = new Date();
    let year = date.getFullYear()
    let month = date.getMonth() + 1;
    let day = date.getDate();
    this.input_time = year + '-' + month + '-' + day;
  },
};
</script>

<style scoped>
.flex {
  display: flex;
  justify-content: space-between;
}
.left {
  display: flex;
  justify-content: flex-start;
}
</style>